﻿using System;

using System.Collections.Generic;
using System.Text;
using PasswordSafe.Properties;
using PasswordSafe.Classes;
using PasswordSafe.Xml;
using PasswordSafe.Templates;

namespace PasswordSafe.ListBoxes
{
    public class CategoryListBox : ListBoxBase
    {
        protected override void InitControl()
        {
            base.InitControl();
            //ShowHeader = false;
            ItemHeight = 32;

            SelectCategoryTemplate template = new SelectCategoryTemplate();
            ItemTemplate = template;

        }

        public List<CategoryListBoxItem> Categories { get; private set; }

        public CategoriesPanel CategoriesPanel { get { return Parent as CategoriesPanel; } }

        public CategoryListBoxItem Item { get { return GetItem(SelectedItemIndex) as CategoryListBoxItem; } }

        protected override void OnItemClick(int index)
        {
            base.OnItemClick(index);
            if (!Item.IsUsed)
            {
                PasswordCategory category = Item.Category;
                if (category != null)
                {
                    ListBuilder.Instance.AddCategory(category.Clone());
                    CategoriesPanel.Close();
                }
            }
        }


        internal void UpdateData()
        {
            Categories = ListBuilder.Instance.DefaultCategories;
            DataSource = Categories;
            this.SelectFirstDataItem();
        }

        public override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
        {
            base.OnKeyDown(e);
            if (!e.Handled)
            {
                switch (e.KeyCode)
                {
                    case System.Windows.Forms.Keys.Right:
                        e.Handled = true;
                        AddItem();
                        break;

                    case System.Windows.Forms.Keys.Left:
                        e.Handled = true;
                        RemoveItem();
                        break;

                }
            }
        }

       

        private void RemoveItem()
        {
            CategoryListBoxItem item = Item as CategoryListBoxItem;
            if (item != null)
            {
                item.IsUsed = false;
                InvalidateItem(SelectedItemIndex);
            }
            
        }

        public override void AddItem()
        {
            CategoryListBoxItem item = Item as CategoryListBoxItem;
            if (item != null)
            {
                item.IsUsed = true;
                InvalidateItem(SelectedItemIndex);
            }
        }
    }
}
